package com.example.lib_base.net.mvvm

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lib_base.net.Res
import com.google.gson.Gson
import kotlinx.coroutines.launch
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody
import java.text.SimpleDateFormat

open class BaseViewModel:ViewModel() {
    fun<T> httpRequest(s:suspend ()-> Res<T>, success:(T)->Unit){
        viewModelScope.launch {
        try {
                val res = s.invoke()
                if (res.code==200){
                    success(res.data)
                }else {
                    Log.i("===",res.message)
                }
            }catch (e:Exception){
            Log.i("===",e.message.toString())
        }
        }
    }
    fun mapToBody(map: Map<String,Any>):RequestBody{
        val toJson = Gson().toJson(map)
        return RequestBody.create("application/json;charset=utf-8".toMediaTypeOrNull(),toJson)
    }
    fun getDataTime(time:Long):String{
        return SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(time)
    }
}